import { RouteRecordRaw } from "vue-router";
import { TypeMyMenuItem } from "./my_menu_type";

/**
 * 根据 router 中的 RouteRecordRaw[] 生成菜单，todo: 对RouteRecordRaw的类型进行自定义
 * 但未排序
 * @param routes RouteRecordRaw[]
 * @param layerNumber 层数，默认从0开始
 * @param itemArray 结果数组，传和不传都ok
 * @returns 
 */
function createMenuItemArrayByRoutes(
    routes: RouteRecordRaw[],
    layerNumber: number = 0,
    itemArray: TypeMyMenuItem[]=[],
    
) {
    routes.forEach((rt) => {
        if (rt.meta && rt.meta.isNavMenu) {
            const rtCopy: TypeMyMenuItem = {
                name: rt.name?.toString() + "",
                path: rt.path,
                title: rt.meta.title + "",
                icon: rt.meta.icon + "",
                layerNumber: layerNumber,
                layerOrder: rt.meta.layerOrder
                    ? new Number(rt.meta.layerOrder).valueOf()
                    : 99,
            };
            itemArray.push(rtCopy);
            if (rt.children && rt.children.length > 0) {
                rtCopy.children = [];
                createMenuItemArrayByRoutes(
                    rt.children,
                    layerNumber + 1,
                    rtCopy.children,
                );
            }
        }
    });

    return itemArray;
}

/**
 * 排序
 * @param itemArray 
 * @returns 
 */
function orderMenuItemArray(itemArray: TypeMyMenuItem[]) {
    itemArray.sort((pre, next) => {
        return pre.layerOrder! - next.layerOrder!;
    });
    itemArray.forEach((e) => {
        if (e.children && e.children.length > 0) {
            orderMenuItemArray(e.children);
        }
    });
    return itemArray;
}

/**
 * 根据 router 中的 RouteRecordRaw[] 生成菜单,并排序，
 * todo: 对RouteRecordRaw的类型进行自定义
 * @param routes RouteRecordRaw[]
 * @param layerNumber 层数，默认从0开始
 * @param itemArray 结果数组，传和不传都ok
 * @returns 
 */
function buildMenuItemArray( 
    routes: RouteRecordRaw[],
    layerNumber: number = 0,
    itemArray: TypeMyMenuItem[]=[]
){
    createMenuItemArrayByRoutes(routes,layerNumber,itemArray);
    orderMenuItemArray(itemArray);
    return itemArray;
}

export {buildMenuItemArray}